<?php

class View {

  /**
   *
   * @var array|string
   */
  protected $_path;

  public function __construct($path) {
    $this->_path = $path;
  }

  /**
   *
   * @param string $key
   * @return bool
   */
  public function __isset($key) {
    return isset($this->$key);
  }

  /**
   *
   * @param string $key
   */
  public function __unset($key) {
    if (isset($this->$key)) {
      unset($this->$key);
    }
  }

  /**
   *
   * @param string|array $spec
   * @param mixed $value
   * @return View 
   */
  public function assign($spec, $value = null) {
    if (is_string($spec)) {
      $this->$spec = $value;
    } elseif (is_array($spec)) {
      foreach ($spec as $key => $val) {
        $this->$key = $val;
      }
    }
    return $this;
  }

  public function render($path = NULL) {
    $real_path = $path ? self::getRealPath($path) : $this->getPath();
    if ($real_path) {
      ob_start();
      Logger::add('render: '. $real_path);
      include $real_path;
      return ob_get_clean();
    }
    echo '<br />not found: ' . $real_path;
  }

  public function getPath() {
    $real_path = NULL;
    do {
      if (@$path = array_shift($this->_path)) {
        $real_path = self::getRealPath($path);
      }
    } while ($real_path == NULL && count($this->_path));
    return $real_path;
  }

  public static function getRealPath($path) {
    Logger::add('check path: '.$path);
    $f = str_replace(array('_','.'), DIRECTORY_SEPARATOR, $path) . '.tpl';
    if (file_exists($filename = TEMPLATE_PATH . DIRECTORY_SEPARATOR . TEMPLATE . DIRECTORY_SEPARATOR . $f)) {
      return $filename;
    } else if (TEMPLATE != 'default' && file_exists($filename = TEMPLATE_PATH . DIRECTORY_SEPARATOR . 'default' . DIRECTORY_SEPARATOR . $f)) {
      return $filename;
    }
  }

}